<template>
  <div class="app-container">
    <h3>用户管理#</h3>

    <div class="filter-container">
      <el-form label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名">
              <el-input
                v-model="listQuery.niceName"
                placeholder="姓名"
                style="width: 200px;"
                class="filter-item"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户名">
              <el-input
                v-model="listQuery.userName"
                placeholder="用户名"
                style="width: 200px;"
                class="filter-item"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工号">
              <el-input
                v-model="listQuery.userNo"
                placeholder="工号"
                style="width: 200px;"
                class="filter-item"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList">查询</el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          class="filter-item"
          @click="addGsForm"
          v-if="hasPermission('clinic:user:add')"
        >
          <span>添加用户</span>
        </el-button>
      </el-form>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="姓名" prop="niceName" align="center" width="100">
        <template slot-scope="{ row }">
          <span>{{ row.niceName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop="userName" align="center" width="100">
        <template slot-scope="{ row }">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="工号" prop="userNo" align="center" width="100">
        <template slot-scope="{ row }">
          <span>{{ row.userNo }}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系电话" prop="mobile" align="center" width="150">
        <template slot-scope="{ row }">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>

      <el-table-column label="科室" prop="deptName" align="center" width="100">
        <template slot-scope="{ row }">
          <span>{{ row.deptName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="角色" prop="role" align="center" width="100">
        <template slot-scope="{ row }">
          <span>{{ row.role }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" prop="locked" align="center" width="100">
        <template slot-scope="{ row }">
          <span>{{ !row.locked ? "正常" : "锁定" }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" prop="id" align="center">
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="mini"
            v-if="hasPermission('clinic:user:change')"
            @click="changepwd(row)"
          >修改密码</el-button>
          <el-button
            type="primary"
            size="mini"
            v-if="hasPermission('clinic:user:edit')"
            @click="addGsForm(row)"
          >编辑用户</el-button>
          <el-button
            type="primary"
            size="mini"
            v-if="hasPermission('clinic:role:user:grant')"
            @click="grantRole(row)"
          >授权角色</el-button>
          <el-button
            type="primary"
            size="mini"
            v-if="hasPermission('clinic:dept:grant')"
            @click="grantDept(row)"
          >调岗部门</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="title"
      class="dialogAdd"
      :visible.sync="dialogUserVisible"
      :width="width"
      top="30px"
    >
      <el-form ref="addForm" :model="userData" :rules="userRules" size="medium" label-width="100px">
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="userData.userName"
            placeholder="请输入用户名"
            clearable
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="员工姓名" prop="niceName">
          <el-input
            v-model="userData.niceName"
            placeholder="请输入员工姓名"
            clearable
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="员工工号" prop="userNo">
          <el-input
            v-model="userData.userNo"
            placeholder="请输入员工工号"
            clearable
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="mobile">
          <el-input
            v-model="userData.mobile"
            placeholder="请输入联系电话"
            clearable
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="deptId" v-if="!userData.userId">
          <el-select
            v-model="userData.deptId"
            placeholder="请选择部门"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option v-for="(item, index) in deptMap" :key="index" :label="item" :value="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleId" v-if="!userData.userId">
          <el-select
            v-model="userData.roleId"
            placeholder="请选择系统角色"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option v-for="(item, index) in roleMap" :key="index" :label="item" :value="index"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="密码" prop="pwd" v-if="!userData.userId">
          <el-input
            v-model="userData.pwd"
            placeholder="请输入密码"
            clearable
            show-password
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password" v-if="!userData.userId">
          <el-input
            v-model="userData.password"
            placeholder="请输入确认密码"
            clearable
            show-password
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>

        <el-form-item label="锁定" prop="locked" required>
          <el-switch v-model="userData.locked"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancelUser">取消</el-button>
        <el-button type="primary" @click="saveUser">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="重置密码"
      class="dialogAdd"
      :visible.sync="dialogUserPwdVisible"
      width="600px"
      top="30px"
    >
      <el-form ref="pwdForm" :model="pwdData" :rules="pwdRules" size="medium" label-width="100px">
        <el-form-item label="密码" prop="checkPwd">
          <el-input
            v-model="pwdData.checkPwd"
            placeholder="请输入密码"
            clearable
            show-password
            :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password">
          <el-input
            v-model="pwdData.password"
            placeholder="请输入确认密码"
            clearable
            show-password
            :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="resetPwd">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="授予角色"
      class="dialogAdd"
      :visible.sync="dialogRoleVisible"
      width="600px"
      top="30px"
    >
      <el-form
        ref="roleForm"
        :model="userData"
        :rules="userRules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="系统角色" prop="roleId">
          <el-select
            v-model="userData.roleId"
            placeholder="请选择系统角色"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option v-for="(item, index) in roleMap" :key="index" :label="item" :value="index"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="grantToRole">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="调岗部门"
      class="dialogAdd"
      :visible.sync="dialogDeptVisible"
      width="600px"
      top="30px"
    >
      <el-form
        ref="deptForm"
        :model="userData"
        :rules="userRules"
        size="medium"
        label-width="100px"
      >
        <el-form-item label="部门" prop="deptId">
          <el-select
            v-model="userData.deptId"
            placeholder="请选择部门"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option v-for="(item, index) in deptMap" :key="index" :label="item" :value="index"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="grantToDept">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUser,
  addUser,
  resetPwd,
  editUser,
  grantRole,
  grantDept
} from "@/api/userManagement";
import { getDept } from "@/api/dept";
import { getRoles } from "@/api/role";
import Pagination from "@/components/Pagination";

export default {
  name: "user",
  components: { Pagination },
  data() {
    return {
      width: "800px",

      pwdData: {
        userId: "",
        checkPwd: "",
        password: ""
      },
      pwdRules: {
        checkPwd: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入确认密码",
            trigger: "blur"
          }
        ]
      },

      userData: {
        userName: "",
        niceName: "",
        userNo: "",
        mobile: "",
        deptId: "",
        roleId: "",
        pwd: "",
        password: "",
        locked: false
      },
      userRules: {
        userName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur"
          }
        ],
        niceName: [
          {
            required: true,
            message: "请输入员工姓名",
            trigger: "blur"
          }
        ],
        userNo: [],
        mobile: [
          {
            required: true,
            message: "请输入联系电话",
            trigger: "blur"
          }
        ],
        deptId: [
          {
            required: true,
            message: "请选择部门",
            trigger: "change"
          }
        ],
        roleId: [
          {
            required: true,
            message: "请选择系统角色",
            trigger: "change"
          }
        ],
        pwd: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "请输入确认密码",
            trigger: "blur"
          }
        ]
      },

      tableKey: 0,
      listLoading: true,
      list: null,
      driver: null,
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 20
      },

      addForm: {},
      dialogUserVisible: false,
      dialogUserPwdVisible: false,
      dialogDeptVisible: false,
      dialogRoleVisible: false,
      title: "",

      deptList: [],
      roleList: [],
      deptMap: {},
      roleMap: {}
    };
  },

  created() {
    window.app = this;
    this.getDeptList(100);
    this.getRoleList(100);
    this.getList();
  },

  mounted: function() {
    // 监听窗口大小变化
    let self = this;
    self.width = window.innerWidth * 0.8 + "px";
  },

  methods: {
    grantToDept() {
      grantDept({
        grantId: this.userData.deptId,
        id: this.userData.userId
      }).then(response => {
        if (response.code === 200) {
          this.close();
          this.getList();
        }
        this.$message({
          showClose: true,
          message: response.msg,
          type: "success"
        });
      });
    },
    grantToRole() {
      grantRole({
        grantId: this.userData.roleId,
        id: this.userData.userId
      }).then(response => {
        if (response.code === 200) {
          this.close();
          this.getList();
        }
        this.$message({
          showClose: true,
          message: response.msg,
          type: "success"
        });
      });
    },
    grantDept(row) {
      this.dialogDeptVisible = true;
      this.userData.userId = row.userId;
    },
    grantRole(row) {
      this.dialogRoleVisible = true;
      this.userData.userId = row.userId;
    },
    close() {
      this.$emit("update:visible", false);
      this.dialogUserPwdVisible = false;
      this.dialogRoleVisible = false;
      this.dialogDeptVisible = false;
    },
    resetPwd() {
      this.$refs["pwdForm"].validate(valid => {
        if (!valid) return;
        if (this.pwdData.checkPwd !== this.pwdData.password) {
          this.$message({
            message: "密码不一致，请重新输入",
            type: "warning"
          });
          this.pwdData.checkPwd = "";
          this.pwdData.password = "";
          return;
        }
        resetPwd(this.pwdData).then(response => {
          if (response.code === 200) {
            this.close();
          } else {
            this.pwdData.checkPwd = "";
            this.pwdData.password = "";
          }
          this.$message({
            showClose: true,
            message: response.msg,
            type: "success"
          });
        });
      });
    },
    cancelUser() {
      this.dialogUserVisible = false;
      this.$emit("update:visible", false);
      this.$refs["addForm"].resetFields();
    },
    saveUser() {
      this.$refs["addForm"].validate(valid => {
        if (!valid) return;
        if (!this.userData.userId) {
          if (this.userData.pwd !== this.userData.password) {
            this.$message({
              showClose: true,
              message: "密码不一致",
              type: "error"
            });
            return;
          }
          addUser(this.userData).then(response => {
            if (response.code === 200) {
              this.cancelUser();
              this.getList();
            } else {
              this.userData.pwd = "";
              this.userData.password = "";
            }
            this.$message({
              showClose: true,
              message: response.msg,
              type: "success"
            });
          });
        } else {
          let p = {
            id: this.userData.userId,
            locked: this.userData.locked,
            mobile: this.userData.mobile,
            niceName: this.userData.niceName,
            userName: this.userData.userName,
            userNo: this.userData.userNo
          };
          editUser(p).then(response => {
            if (response.code === 200) {
              this.cancelUser();
              this.getList();
            }
            this.$message({
              showClose: true,
              message: response.msg,
              type: "success"
            });
          });
        }
      });
    },
    getRoleList(pageSize) {
      getRoles({ page: 1, pageSize: pageSize }).then(response => {
        if (response.code === 200) {
          this.roleList = response.data;
          this.roleList.map(item => {
            this.roleMap[item.id] = item.role;
          });
        }
      });
    },
    getDeptList(pageSize) {
      if (this.deptList.length > 0) {
        return false;
      }

      getDept({ page: 1, pageSize: pageSize }).then(response => {
        if (response.code === 200) {
          this.deptList = response.data;
          this.deptList.map(item => {
            this.deptMap[item.id] = item.deptName;
          });
        }
      });
    },
    addGsForm(row) {
      console.log(row);
      this.dialogUserVisible = true;
      if (row.userId) {
        this.title = "编辑用户";
        this.userData = row;
        this.userData.pwd = 1;
        this.userData.password = 1;
        this.userData.roleId = 1;
        this.userData.deptId = 1;
      } else {
        this.title = "新增用户";
        this.userData = {
          userName: null,
          niceName: null,
          userNo: null,
          mobile: null,
          deptId: null,
          roleId: null,
          pwd: null,
          password: null,
          locked: false
        };
      }
    },
    resetForm: function(addForm) {
      if (addForm.password !== addForm.pwd) {
        this.$message({
          message: "密码不一致，请重新输入",
          type: "warning"
        });
        addForm.password = "";
        addForm.pwd = "";
        return false;
      }
      this.listLoading = true;
      resetPwd(addForm).then(response => {
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 0.5 * 1000);

        if (response.code == 200) {
          this.$message("密码重置成功");
          this.getList();
        }
        console.log(response);
        this.dialogRoleVisible = false;
      });
    },
    saveAddForm(addForm) {
      if (!addForm.id && addForm.password !== addForm.pwd) {
        this.$message({
          message: "密码不一致，请重新输入",
          type: "warning"
        });
        addForm.password = "";
        addForm.pwd = "";
        return false;
      }

      addForm.deptCode = addForm.deptCode;
      addForm.deptName = this.deptMap[addForm.deptCode];
      this.listLoading = true;
      if (!addForm.id) {
        addUser(addForm).then(response => {
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false;
          }, 0.5 * 1000);

          if (response.code == 200) {
            this.getList();
            this.$message("新增用户成功");
          }
          console.log(response);
          this.dialogRoleVisible = false;
        });
      } else {
        delete addForm.password;
        editUser(addForm).then(response => {
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false;
          }, 0.5 * 1000);

          if (response.code == 200) {
            this.getList();
            this.$message("修改用户成功");
          }
          console.log(response);
          this.dialogRoleVisible = false;
        });
      }
    },
    getList() {
      console.log(this);
      this.listLoading = true;

      getUser(this.listQuery).then(response => {
        console.log(response);
        this.list = response.page.list;
        this.total = response.page.totalCount;

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 0.5 * 1000);
      });
    },
    dialogDeptVisibleClick() {
      this.getDeptList();
      this.title = "科室授权";
      this.dialogUserVisible = true;
      this.listLoading = true;
    },
    changepwd(row) {
      this.dialogUserPwdVisible = true;
      this.pwdData.userId = row.userId;
      this.pwdData.checkPwd = "";
      this.pwdData.password = "";
    },
    deptData() {
      alert("查询科室");
    },
    dialogRoleVisibleData() {
      alert("查询角色");
    }
  }
};
</script>
